{extend name="common/layout" /}
{block name="main"}
<div class="el-breadcrumb">
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item>房屋管理</el-breadcrumb-item>
    <el-breadcrumb-item>未收账单</el-breadcrumb-item>
  </el-breadcrumb>
</div>

<el-button type="primary" @click="concentrated('e')" icon="el-icon-edit-outline">集中抄电</el-button>
<el-button type="primary" @click="concentrated('w')" icon="el-icon-edit-outline">集中抄水</el-button>

<span style="padding-left: 10px;"></span>
<el-date-picker v-model="meter_reading_time" value-format="YYYY-MM-DD" type="date" placeholder="选择抄表日期"
  @change="changeDate">
</el-date-picker>
<span class="el-right">
  <el-button icon="el-icon-brush" @click="handleBrush"></el-button>
  <el-button icon="el-icon-printer" @click="handlePrintAll"></el-button>
</span>

<div style="margin-top: 15px;" id="printJS-form333">
  <el-table :data="tableData" stripe border style="width: 100%" @sort-change="handleSort">
    <el-table-column label="" width="59" key="slot" v-if="print == true">
      <template #default="scope">
        <el-button> </el-button>
      </template>
    </el-table-column>
    <el-table-column prop="property_name" label="房产" width="100">
    </el-table-column>
    <el-table-column prop="name" label="房号" sortable="custom" width="100">
    </el-table-column>
    <el-table-column prop="total_money" label="金额" width="60">
    </el-table-column>
    <el-table-column prop="start_time" label="收款日期" v-if="print == false" width="180">
    </el-table-column>
    <el-table-column prop="meter_reading_time" label="抄表日期" v-if="print == false" width="180">
    </el-table-column>
    <el-table-column label="" width="59" key="slot" v-if="print == true">
      <template #default="scope">
        <el-button> </el-button>
      </template>
    </el-table-column>
    <el-table-column label="操作" key="slot" v-if="print == false">
      <template #default="scope">
        <el-button size="mini" type="primary" @click="handleMeter(scope.row)" icon="el-icon-edit">抄表</el-button>
        <el-button size="mini" type="success" v-if="scope.row.note != '借贷平衡'" @click="handlePrint(scope.row)"
          icon="el-icon-postcard">收据</el-button>
        <el-button size="mini" type="warning" @click="handleAccount(scope.row)" icon="el-icon-check">到账</el-button>
        <el-button size="mini" type="info" v-if="scope.row.note != '借贷平衡'" @click="handleHistory(scope.row)"
          icon="el-icon-time">历史账单</el-button>
        <el-button size="mini" type="danger" v-if="scope.row.end_time != null" @click="handleBalance(scope.row)"
          icon="el-icon-umbrella">借贷</el-button>
      </template>
    </el-table-column>
  </el-table>
</div>
<div style="margin-top: 15px;">
  <el-pagination background layout="total, sizes, prev, pager, next" :total="pageTotal" :page-sizes="[10, 20, 50]"
    :page-size="10" v-model::current-page="currentPage" @current-change="changeTable" @size-change="handleSizeChange">
  </el-pagination>
</div>

<!-- 收据预览 -->
<el-dialog title="收据" v-model="printVisible" top="5vh" width="42%" :destroy-on-close="true">
  <v-form-render :form-json="formJson" :form-data="formData" :option-data="optionData" ref="vFormRef">
  </v-form-render>
  <template #footer>
    <span class="dialog-footer">
      <el-button type="primary" @click="handlePrintData()">打 印</el-button>
      <el-popover placement="top" :width="330" trigger="click" :auto-close="1500">
        <template #reference>
          <el-button type="primary">历史水电</el-button>
        </template>
        <el-table :data="historyData" border>
          <el-table-column width="85" property="start_time" label="租期"></el-table-column>
          <el-table-column width="60" property="electricity_consumption" label="用电量"></el-table-column>
          <el-table-column width="60" property="water_consumption" label="用水量"></el-table-column>
          <el-table-column width="125" property="note" label="备注"></el-table-column>
        </el-table>
      </el-popover>
      <el-button @click="printVisible = false">取 消</el-button>
    </span>
  </template>
</el-dialog>

<!-- 历史账单 -->
<el-dialog title="历史账单" v-model="historyBillVisible" top="5vh">
  <el-table :data="historyBillData" border>
    <el-table-column property="number_name" label="房号" width="60"></el-table-column>
    <el-table-column property="start_time" label="租期"></el-table-column>
    <el-table-column property="electricity_meter_this_month" label="本月电表度数" width="95"></el-table-column>
    <el-table-column property="electricity_consumption" label="用电量"></el-table-column>
    <el-table-column property="water_meter_this_month" label="本月水表度数" width="95"></el-table-column>
    <el-table-column property="water_consumption" label="用水量"></el-table-column>
    <el-table-column property="total_money" label="总金额"></el-table-column>
    <el-table-column property="note" label="备注" width="130"></el-table-column>
  </el-table>
</el-dialog>

<!-- 抄表 -->
<el-dialog :title="tableTitle" v-model="meterVisible" top="5vh">
  <el-form :model="meterData" :rules="meterRules" ref="meterData">
    <el-form-item label="上月电表度数" :label-width="formLabelWidth" prop="electricity_meter_last_month">
      <el-input v-model.number="meterData.electricity_meter_last_month" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="上月水表度数" :label-width="formLabelWidth" prop="water_meter_last_month">
      <el-input v-model.number="meterData.water_meter_last_month" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="抄表日期" :label-width="formLabelWidth" prop="meter_reading_time">
      <el-date-picker type="date" v-model="meterData.meter_reading_time" value-format="YYYY-MM-DD" placeholder="选择日期"
        style="width: 100%;">
      </el-date-picker>
    </el-form-item>
    <el-form-item label="本月电表度数" :label-width="formLabelWidth" prop="electricity_meter_this_month">
      <el-input v-model.number="meterData.electricity_meter_this_month" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="本月水表度数" :label-width="formLabelWidth" prop="water_meter_this_month">
      <el-input v-model.number="meterData.water_meter_this_month" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="租金" :label-width="formLabelWidth" prop="rental">
      <el-input v-model.number="meterData.rental" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="押金" :label-width="formLabelWidth" prop="deposit">
      <el-input v-model.number="meterData.deposit" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="管理费" :label-width="formLabelWidth" prop="management">
      <el-input v-model.number="meterData.management" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="其他费用" :label-width="formLabelWidth" prop="other_charges">
      <el-input v-model="meterData.other_charges"></el-input>
    </el-form-item>
    <el-form-item label="备注" :label-width="formLabelWidth" prop="note">
      <el-input v-model="meterData.note"></el-input>
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="meterVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSave()">确 定</el-button>
    </span>
  </template>
</el-dialog>

<!-- 集中抄表 -->
<el-dialog :title="concentratedTitle" v-model="concentratedVisible" top="5vh">
  <el-form :model="concentratedData" ref="concentratedData">
    <el-form-item v-if="concentratedType == 'e'" v-for="(domain, index) in concentratedData"
      :label-width="formLabelWidth" :label="domain.name + '-'+ domain.electricity_meter_last_month" :key="domain.id">
      <el-input v-model="domain.electricity_meter_this_month"></el-input>
    </el-form-item>
    <el-form-item v-if="concentratedType == 'w'" v-for="(domain, index) in concentratedData"
      :label-width="formLabelWidth" :label="domain.name + '-'+ domain.water_meter_last_month" :key="domain.id">
      <el-input v-model="domain.water_meter_this_month"></el-input>
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="concentratedVisible = false">取 消</el-button>
      <el-button type="primary" @click="concentratedSave()">确 定</el-button>
    </span>
  </template>
</el-dialog>
{/block}

{block name="script"}
<script>
  const data = {
    tableData: [],
    meterVisible: false,
    formLabelWidth: '120px',
    meterData: {},
    meterRules: {
      electricity_meter_last_month: [{ required: true, message: '请输入', trigger: 'blur' }, { type: 'number', message: '必须为数字值' }],
      water_meter_last_month: [{ required: true, message: '请输入', trigger: 'blur' }, { type: 'number', message: '必须为数字值' }],
      meter_reading_time: [{ required: true, message: '请选择', trigger: 'change' }],
      electricity_meter_this_month: [{ required: true, message: '请输入', trigger: 'blur' }, { type: 'number', message: '必须为数字值' }],
      water_meter_this_month: [{ required: true, message: '请输入', trigger: 'blur' }, { type: 'number', message: '必须为数字值' }],
      rental: [{ required: true, message: '请输入', trigger: 'blur' }, { type: 'number', message: '必须为数字值' }],
      deposit: [{ required: true, message: '请输入', trigger: 'blur' }, { type: 'number', message: '必须为数字值' }],
      management: [{ required: true, message: '请输入', trigger: 'blur' }, { type: 'number', message: '必须为数字值' }],
      other_charges: [{ required: true, message: '请输入', trigger: 'blur' }],
    },
    // 日期选择器
    meter_reading_time: '',
    // 分页
    pageTotal: 0,
    currentPage: 1,
    currentLimit: 10,
    // 排序
    field: '',
    order: '',
    // 打印全部
    print: false,
    // 收据显示
    printVisible: false,
    printId: '',
    // vform3
    formJson: {},
    formData: {},
    optionData: {},
    // 历史水电
    historyData: [],
    // 历史账单
    historyBillVisible: false,
    historyBillData: [],
    // 抄表标题
    tableTitle: '',
    // 集中抄表标题
    concentratedTitle: '',
    concentratedVisible: false,
    concentratedData: [],
    concentratedType: '',
    // 当前日期
    today: new Date()
  }
  function f() {
    return {
      init: function () {
        this.queryTable();
      },
      queryTable: function (params) {
        let that = this;
        axiosGet("{:url('query')}", params).then(response => {
          if (response.code == 1) {
            that.tableData = response.data;
            that.pageTotal = response.count;
          } else {
            that.$message.error('系统出错了!!!');
          }
        });
      },
      querSort: function () {
        let params = {
          'meter_reading_time': this.meter_reading_time,
          'house_property_id': this.houseDef,
          'field': this.field,
          'order': this.order,
          'page': this.currentPage,
          'limit': this.currentLimit,
        }
        this.queryTable(params);
      },
      // 字段排序查询
      handleSort: function (val) {
        let order = '';
        if (val.order == 'ascending') {
          order = 'asc';
        } else if (val.order == 'descending') {
          order = 'desc';
        }
        let params = {
          'meter_reading_time': this.meter_reading_time,
          'house_property_id': this.houseDef,
          'field': val.prop,
          'order': order,
          'page': this.currentPage,
          'limit': this.currentLimit,
        }
        this.queryTable(params);
        this.field = val.prop
        this.order = order
      },
      // 分页-选择(下一页)查询
      changeTable(val) {
        let params = {
          'meter_reading_time': this.meter_reading_time,
          'house_property_id': this.houseDef,
          'field': this.field,
          'order': this.order,
          'page': val,
          'limit': this.currentLimit,
        }
        this.currentPage = val
        this.queryTable(params);
      },
      // 分页-切换每页条数查询
      handleSizeChange(val) {
        let params = {
          'meter_reading_time': this.meter_reading_time,
          'house_property_id': this.houseDef,
          'field': this.field,
          'order': this.order,
          'page': this.currentPage,
          'limit': val,
        }
        this.queryTable(params);
      },
      // 切换抄表日期查询
      changeDate(val) {
        let params = {
          'meter_reading_time': val,
          'house_property_id': this.houseDef,
          'field': this.field,
          'order': this.order,
          'page': this.currentPage,
          'limit': this.currentLimit,
        }
        this.queryTable(params);
      },
      // 到账
      handleAccount(row) {
        let that = this;
        this.$confirm(row.name + '的' + row.total_money + '元已到账？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          // type: 'warning'
        }).then(() => {
          axiosPost("{:url('account')}", { id: row.id }).then(response => {
            if (response.state == 'success') {
              that.$message.success(response.msg)
              that.querSort();
            } else {
              that.$message({
                message: response.msg, type: response.state
              });
            }
          });
        }).catch(() => { });
      },
      // 借贷
      handleBalance(row) {
        let that = this;
        this.$confirm('是否借贷', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          // type: 'warning'
        }).then(() => {
          axiosPost("{:url('balance')}", { id: row.id }).then(response => {
            if (response.state == 'success') {
              that.$message.success(response.msg)
              that.querSort();
            } else {
              that.$message({
                message: response.msg, type: response.state
              });
            }
          });
        }).catch(() => { });
      },
      // 历史账单
      handleHistory(row) {
        this.historyBillVisible = true;
        let that = this;
        let params = {
          number_id: row.house_number_id,
          property_id: row.house_property_id,
          tenant_id: row.tenant_id
        };
        axiosGet("{:url('queryHistory')}", params).then(response => {
          if (response.code == 1) {
            that.historyBillData = response.data;
          } else {
            that.$message.error('系统出错了!!!');
          }
        });
      },
      // 抄表
      handleMeter(row) {
        this.meterVisible = true;
        this.tableTitle = row.property_name + '-' + row.name;
        this.meterData = JSON.parse(JSON.stringify(row));
        if (!this.meterData.meter_reading_time) {
          let mdy = new Date().toLocaleDateString().split('/');
          let month = parseInt(mdy[1]);
          if (month >= 1 && month <= 9) {
            month = "0" + month;
          }
          let strDate = parseInt(mdy[2]);
          if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
          }
          this.meterData.meter_reading_time = parseInt(mdy[0]) + '-' + month + '-' + strDate
        }
        if (this.$refs['meterData']) {
          this.$refs['meterData'].resetFields();
        }
      },
      // 保存抄表数据
      handleSave() {
        let that = this;
        let validation = false;
        this.$refs['meterData'].validate((valid) => {
          if (valid) {
            validation = true;
          }
        });
        if (validation) {
          axiosPost("{:url('save')}", this.meterData).then(response => {
            if (response.state == 'success') {
              that.$message.success(response.msg)
              that.meterVisible = false
              that.querSort();
            } else {
              that.$message({
                message: response.msg, type: response.state
              });
            }
          });
        }
      },
      // 集中抄表
      concentrated(val) {
        if (val == 'e') {
          this.concentratedTitle = '集中抄电'
        } else if (val == 'w') {
          this.concentratedTitle = '集中抄水'
        }
        this.concentratedType = val
        this.concentratedVisible = true
        let that = this
        axiosGet("{:url('centralized')}", { type: val, house_property_id: this.houseDef }).then(response => {
          if (response.code == 1) {
            that.concentratedData = response.data;
          } else {
            that.$message.error('系统出错了!!!');
          }
        });
      },
      // 集中抄表保存
      concentratedSave() {
        let that = this
        let postData = {}
        if (this.concentratedType == 'e') {
          this.concentratedData.forEach(element => {
            if (element.electricity_meter_this_month) {
              postData[element.id] = element.electricity_meter_this_month
            }
          });
        } else if (this.concentratedType == 'w') {
          this.concentratedData.forEach(element => {
            if (element.water_meter_this_month) {
              postData[element.id] = element.water_meter_this_month
            }
          });
        }
        axiosPost("{:url('saveCentralized')}", { data: postData, type: this.concentratedType }).then(response => {
          if (response.state == 'success') {
            that.$message.success(response.msg)
            that.concentratedVisible = false
            that.querSort();
          } else {
            that.$message({
              message: response.msg, type: response.state
            });
          }
        });
      },
      // 打印table
      handlePrintAll() {
        printJS({
          printable: 'printJS-form333',
          type: 'html',
          header: '打印时间：' + new Date().toLocaleDateString(),
          headerStyle: 'font-weight: 100; font-size: 12px;',
          // css: '__CDN__/print/print.css'
          css: '__STATIC__/css/print.css?{if $Think.env.app_debug}_={:time()}{else /}v={$Think.config.tpadmin.version}{/if}'
          // style: 'width: 100%; border-collapse: collapse; border-spacing: 0;'
        })
      },
      // 打印收据
      handlePrintData() {
        window.open('{:url("print")}' + '?id=' + this.printId, "_blank")
      },

      handleBrush() {
        this.print = !this.print;
      },
      // 查看收据
      handlePrint(row) {
        this.printId = row.id
        let that = this;
        axiosGet("{:url('queryData')}", { id: row.id }).then(response => {
          if (response.code == 1) {
            that.formJson = response.data.end_time ? formJson : formJson1;
            that.formData = response.data;
            this.printVisible = true;
          } else {
            that.$message.error('系统出错了!!!');
          }
        });
        axiosGet("{:url('queryWater')}", { number_id: row.house_number_id, tenant_id: row.tenant_id }).then(response => {
          if (response.code == 1) {
            that.historyData = response.data;
          } else {
            that.$message.error('系统出错了!!!');
          }
        });
      },
    }
  }
</script>
{/block}